package org.flexlancer.managers
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	
	import org.flexlancer.Logger.Logger;
	import org.flexlancer.enums.AppVariables;
	import org.flexlancer.events.AssetEvent;
	import org.flexlancer.utils.GeneralUtils;

	public class AssetManager extends EventDispatcher
	{
		private var assets_list:XMLList ;
		public var assets:Dictionary = new Dictionary;
		private var loader_index:int;
		
		public function AssetManager()
		{
			super(null);
		}
		
		public function LoadAssets(parmAssetsList:XMLList):void{
			try{
				this.assets_list = parmAssetsList;
				this.loader_index = -1;
				this.LoadNext();
			}catch(err:Error){
				throw err;
			}
		}
		
		private function LoadNext():void{
			try{
				if ( this.loader_index >= this.assets_list.length() - 1 ){
					this.dispatchEvent(new AssetEvent(AssetEvent.ASSETS_LOADED));
					return;
				}
				
				this.loader_index++;
				
				var xitem:XML = new XML(this.assets_list[this.loader_index]);
				var url:String = AppVariables.SERVER_URL + String(xitem.URL);
				var ldr:URLLoader = new URLLoader;
				var req:URLRequest = new URLRequest(url);
				
				ldr.addEventListener(Event.COMPLETE,OnSingleAssetLoadComplete,false,0,true);
				ldr.addEventListener(IOErrorEvent.IO_ERROR,OnSingleAssetsLoadError,false,0,true);
				
				ldr.load(req);
				GeneralUtils.Show(String(xitem.Name));
			}catch(err:Error){
				throw err;
			}
		}
		
		private function MakeAssetObject():Object{
			try{
				var xitem:XML = new XML(this.assets_list[this.loader_index]);
				var retObj:Object = new Object;
				
				retObj.Name = String(xitem.Name);
				retObj.Type = String(xitem.localName());
				retObj.URL = String(xitem.URL);
				
				return retObj; 
			}catch(err:Error){
				throw err;
			}
			return new Object;
		}
		
		private function OnSingleAssetLoadComplete(evt:Event):void{
			try{
				var dictObj:Object = this.MakeAssetObject();
				dictObj.value = new XML(evt.target.data);
				this.assets[dictObj.Name] = dictObj;
				
				this.LoadNext();
				GeneralUtils.Hide();
			}catch(err:Error){
				Logger.LogE(err);
			}
		}
		
		private function OnSingleAssetsLoadError(evt:IOErrorEvent):void{
			try{
				var dictObj:Object = this.MakeAssetObject();
				dictObj.value = "FAILED";
				this.assets[dictObj.Name] = dictObj;
				
				this.LoadNext();
				GeneralUtils.Hide();
			}catch(err:Error){
				Logger.LogE(err);
			}
		}
	}
}